import { defineStore } from "pinia";
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user";
import { loginFormData, loginResponseData, userInfoResponseData } from "@/api/users/type";
import { UserState } from "./types/types";
// 引入操作本地存储的工具方法
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
// 引入常量路由
import { constantRoute } from "@/router/routes";

// 创建用户小仓库
let useUserStore = defineStore('User', {
  // 小仓库数据
  state: (): UserState => {
    return {
      token: GET_TOKEN(),  //用户唯一标识token
      menuRoutes: constantRoute,
      username: '',
      avatar: ''
    }
  },
  // 小仓库的异步|逻辑
  actions: {
    // 用户登录方法
    async userLogin(data: loginFormData) {
      let result: loginResponseData = await reqLogin(data)
      if (result.code == 200) {
        this.token = (result.data as string)
        SET_TOKEN(this.token)
        return 'OK'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },

    //获取用户信息
    async userInfo() {
      let result:userInfoResponseData = await reqUserInfo()
      // console.log(result.data)
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    // 退出登录
    async userLogout() {
      let result:any = await reqLogout()
      if (result.code == 200) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    }
  },
  getters: {

  }
})

export default useUserStore